<template>
  <div
    v-loading="loading"
    class="edu-page-warp">
    <div class="edu-page-title">
      {{ $t('classroom.classroomManage') }}
    </div>
    <el-row :gutter="24">
      <el-col :span="6">
        <el-card
          shadow="never"
          body-style="padding: 24px;">
          <el-tree
            :load="loadNode"
            :props="defaultProps"
            lazy
            @node-click="handleNodeClick"/>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card
          shadow="never"
          body-style="padding: 24px 24px 6px 24px;">
          <el-form
            ref="queryForm"
            :model="queryForm"
            label-position="left"
            label-width="80px">
            <el-row
              :gutter="24"
              style="height: 50px;">
              <el-col :span="8">
                <el-form-item
                  :label="$t('message.name') + ':'"
                  prop="name">
                  <el-input
                    v-model="queryForm.name"
                    :placeholder="$t('message.plsInput')"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="$t('message.department') + ':'"
                  prop="departmentCode">
                  <el-select
                    v-model="queryForm.departmentCode"
                    style="width: 100%">
                    <el-option
                      v-for="item in options.departmentCode"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="$t('message.type') + ':'"
                  prop="type">
                  <el-select
                    v-model="queryForm.type"
                    style="width: 100%">
                    <el-option
                      v-for="item in options.roomTypes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              :gutter="24"
              style="height: 50px;">
              <el-col :span="8">
                <el-form-item
                  :label="$t('message.use') + ':'"
                  prop="useing">
                  <el-select
                    v-model="queryForm.useing"
                    style="width: 100%">
                    <el-option
                      :label="$t('classroom.planCourse')"
                      value="1"/>
                    <el-option
                      :label="$t('classroom.planExam')"
                      value="2"/>
                    <el-option
                      :label="$t('classroom.activity')"
                      value="4"/>
                    <el-option
                      :label="$t('message.other')"
                      value="3"/>

                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="$t('message.status') + ':'"
                  prop="status">
                  <el-select
                    v-model="queryForm.status"
                    style="width: 100%">
                    <el-option
                      :label="$t('message.enable')"
                      value="0"/>
                    <el-option
                      :label="$t('message.disable')"
                      value="1"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="float-right">
                  <el-button
                    size="mini"
                    @click="handleResetQuery('queryForm')">{{ $t('message.reset') }}
                  </el-button>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleFilterQuery">{{ $t('message.filter') }}
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <div class="edu-page-title mg-top">
          {{ $t('classroom.classroomList') }}
        </div>
        <el-card
          v-loading="loading"
          shadow="never"
          body-style="padding: 24px;">
          <div class="edu-opertion-bar">

            <div class="float-right">
              <!-- <el-button @click="handleDelAll">{{ $t('message.delete') }}</el-button> -->
              <el-button
                type="primary"
                @click="handleAddRoom('roomForm')">{{ $t('message.add') }}
              </el-button>
            </div>
          </div>
          <el-table
            :data="tableData"
            stripe
            style="width: 100%"
            @select="selectRow"
            @selection-change="selectionChange">
            <el-table-column
              type="selection"
              width="55"/>
            <el-table-column
              :label="$t('message.code')"
              prop="code">
              <template slot-scope="scope">
                <el-popover
                  :content="scope.row.code"
                  placement="top-start"
                  trigger="hover">
                  <span slot="reference">{{ scope.row.code }}</span>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('message.name')"
              prop="name">
              <template slot-scope="scope">
                <el-popover
                  :content="scope.row.name"
                  placement="top-start"
                  trigger="hover">
                  <span slot="reference">{{ scope.row.name }}</span>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('message.type')"
              prop="type">
              <template slot-scope="scope">
                <el-tag type="info">{{ scope.row.typeI18n }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('message.department')"
              prop="departmentCode">
              <template slot-scope="scope">
                <el-popover
                  :content="scope.row.departmentCode"
                  placement="top-start"
                  trigger="hover">
                  <span slot="reference">{{ scope.row.departmentCode }}</span>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('classroom.classNumber')"
              prop="classNumber"/>
            <el-table-column
              :label="$t('classroom.examinationNumber')"
              prop="examNumber"/>
            <el-table-column
              :label="$t('message.use')"
              prop="useing"
              width="180">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,idx) in scope.row.useing"
                  :key="idx"
                  style="margin: 0 4px;"
                  type="success">
                  <span
                    v-if="item == 1">{{ $t('classroom.planCourse') }}</span>
                  <span
                    v-if="item == 2">{{ $t('classroom.planExam') }}</span>
                  <span
                    v-if="item == 4">{{ $t('classroom.activity') }}</span>
                  <span
                    v-if="item == 3">{{ $t('message.other') }}</span>
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('message.status')"
              prop="status"
              width="80">
              <template slot-scope="scope">
                <el-tag
                  v-if="scope.row.status == 0"
                  type="success">{{ $t('message.enable') }}
                </el-tag>
                <el-tag
                  v-if="scope.row.status == 1"
                  type="info">{{ $t('message.disable') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('message.operating')"
              width="48px">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleUpdateOne(scope.row)">{{ $t('message.edit') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="edu-pagination">
            <div class="float-right">
              <el-pagination
                :current-page="queryForm.pageNum_"
                :page-sizes="[20,50,100,500,1000]"
                :page-size="queryForm.pageSize_"
                :total="queryForm.total"
                layout="total, sizes, prev, pager, next, jumper"
                style="float: right;margin:0;"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"/>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      :visible.sync="addClassRoomVisible"
      :before-close="handleClose"
      :title="!this.roomForm.code ? $t('message.add') : $t('message.edit')"
      width="60%">
      <el-form
        ref="roomForm"
        :model="roomForm"
        :rules="roomRules"
        label-position="left"
        label-width="120px">
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="名称:"
              prop="name">
              <el-input
                v-model="roomForm.name"
                type="text"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="英文名称:"
              prop="nameEn">
              <el-input
                v-model="roomForm.nameEn"
                type="text"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="教室类型:"
              prop="type">
              <el-select
                v-model="roomForm.type"
                style="width: 100%;">
                <el-option
                      v-for="item in options.roomTypes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="校区:"
              prop="campus">
              <el-select
                v-model="roomForm.campus"
                filterable
                style="width: 100%;"
                @change="handelCampusChang">
                <el-option
                  v-for="item in options.campus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="教学楼:"
              prop="tower">
              <el-select
                v-model="roomForm.tower"
                style="width: 100%;"
                @change="handelTowerChang">
                <el-option
                  v-for="item in options.tower"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="楼层:"
              prop="towerManagementId">
              <el-select
                v-model="roomForm.towerManagementId"
                style="width: 100%;">
                <el-option
                  v-for="item in options.towerManagementId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="使用部门:"
              prop="departmentCode">
              <el-select
                v-model="roomForm.departmentCode"
                filterable
                style="width: 100%;">
                <el-option
                  v-for="item in options.departmentCode"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="用处:"
              prop="useing">
              <el-select
                v-model="roomForm.useing"
                multiple
                style="width: 100%;">
                <el-option
                  label="排课"
                  value="1"/>
                <el-option
                  label="排考"
                  value="2"/>
                <el-option
                  label="活动"
                  value="4"/>
                <el-option
                  label="其它"
                  value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="上课人数:"
              prop="classNumber">
              <el-input-number
                v-model="roomForm.classNumber"
                style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="考试人数:"
              prop="examNumber">
              <el-input-number
                v-model="roomForm.examNumber"
                style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="启用:"
              prop="status">
              <el-select
                v-model="roomForm.status"
                style="width: 100%;">
                <el-option
                  label="启用"
                  value="0"/>
                <el-option
                  label="废弃"
                  value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="联系人:"
              prop="contactPerson">
              <el-input
                v-model="roomForm.contactPerson"
                type="text"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="24"
          style="height: 50px;">
          <el-col :span="12">
            <el-form-item
              label="联系电话:"
              prop="contactPhone">
              <el-input
                v-model="roomForm.contactPhone"
                type="text"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model="roomForm.remark"
                type="text"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancelDialog('roomForm')">{{ $t("message.cancel") }}</el-button>
        <el-button
          type="primary"
          @click="saveRoom('roomForm')">{{ $t("message.confirm") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {queryDic} from "common/src/api/dictionary";
  import * as API from "common/src/api/resource/classroom"
  import UTILS from "common/src/utils/utils";

  export default {
    name: "classroom",
    data() {
      return {
        tableData: [],
        addClassRoomVisible: false,
        queryForm: {
          pageNum_: 0,
          pageSize_: 20,
          total: 0,
          name: '',
          departmentCode: '',
          type: '',
          useing: '',
          status: '',
          campus: '',
          tower: '',
          towerManagementId: ''
        },
        roomForm: {
          name: '',
          nameEn: '',
          code: '',
          type: '',
          campus: '',
          tower: '',
          towerManagementId: '',
          departmentCode: '',
          useing: '',
          status: '',
          contactPerson: '',
          contactPhone: '',
          remark: '',
          classNumber: '',
          examNumber: ''
        },
        options: {
          campus: [],
          departmentCode: [],
          tower: [],
          towerManagementId: [],
          roomTypes: []
        },
        roomRules: {
          name: [
            {required: true, message: this.$t('message.plsInputName'), trigger: 'blur'}
          ],
          campus: [
            {required: true, message: this.$t('common.pla.plsSelectRecord'), trigger: 'blur'}
          ],
          tower: [
            {required: true, message: this.$t('common.pla.plsSelectRecord'), trigger: 'blur'}
          ],
          towerManagementId: [
            {required: true, message: this.$t('common.pla.plsSelectRecord'), trigger: 'blur'}
          ],
          departmentCode: [
            {required: true, message: this.$t('common.pla.plsSelectRecord'), trigger: 'blur'}
          ],
          useing: [
            {required: true, message: this.$t('common.pla.plsSelectRecord'), trigger: 'blur'}
          ]
        },
        data: [{
          label: '同济大学',
          children: []
        }],
        defaultProps: {
          label: 'name',
          children: 'children',
          isLeaf: 'leaf'
        },
      }
    },
    methods: {
      async init() {
        let res = await API.findClassroomList(this.queryForm);
        if (res && res.code == 200) {
          _.forEach(res.data.list, function(item) {
            if(item.useing!=null){
              item.useing = item.useing.split(',');
            }
            
          });
          this.tableData = res.data.list;
          this.queryForm.total = res.data.total_;
        }
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum_ = val;
        this.init(this.queryForm);
      },
      handleSizeChange(val) {
        this.queryForm.pageSize_ = val;
        this.init(this.queryForm);
      },
      handleFilterQuery() {
        this.init(this.queryForm);
      },
      handleResetQuery(formName) {
        this.$refs[formName].resetFields();
        this.init();
      },
      handleNodeClick(data, checked) {
        let _this = this;
         if(checked.level === 1) {
           _.forEach(this.queryForm, function(item, key) {
             if(!_.includes(['pageNum_', 'pageSize_'], key)) {
               _this.queryForm[key] = '';
             }
           })
           this.init();
         }
         if(checked.level === 2) {
           _.forEach(this.queryForm, function(item, key) {
             if(!_.includes(['pageNum_', 'pageSize_'], key)) {
               _this.queryForm[key] = '';
             }
           })
           this.queryForm.campus = checked.data.id;
           this.init();
         }
         if(checked.level === 3) {
           _.forEach(this.queryForm, function(item, key) {
             if(!_.includes(['pageNum_', 'pageSize_'], key)) {
               _this.queryForm[key] = '';
             }
           })
           this.queryForm.tower = checked.data.id;
           this.init();
         }
         if(checked.level === 4) {
           _.forEach(this.queryForm, function(item, key) {
             if(!_.includes(['pageNum_', 'pageSize_'], key)) {
               _this.queryForm[key] = '';
             }
           })
           this.queryForm.towerManagementId = checked.data.id;
           this.init();
         }

      },
      loadNode(node, resolve) {
        let data = {
          lang: this.$store.getters.language || "cn",
          type: "allChild",
          keys: ["X_XQ"]
        },
        schools = [],
        towers = [],
        levels = [];

          if (node.level === 0) {
            return resolve([{ name: '同济大学' }]);
          }

          if (node.level === 1) {
            queryDic(data)
              .then(res => {
                if (res && res.code == 200) {
                  _.forEach(res.data['X_XQ'], function(val, key) {
                    let school = {
                      id: key,
                      name: val
                    }
                    schools.push(school);
                  })
                  return resolve(schools)
                }
            })
          }

          if (node.level === 2) {
            let params = {
              parentId: node.data.id,
              type: 0
            };
            API.getTower(params).then(res => {
               if(res && res.code == 200) {
                 _.forEach(res.data, function(item) {
                   let tower = {
                     id: item.id,
                     name: item.name
                   }
                   towers.push(tower)
                 });
                 return resolve(towers)
               }
            })
          }

          if (node.level === 3) {
            let params = {
              parentId: node.data.id,
              type: 1
            };
            API.getTower(params).then(res => {
               if(res && res.code == 200) {
                 _.forEach(res.data, function(item) {
                   let level = {
                     id: item.id,
                     name: item.name,
                     leaf: true
                   }
                   levels.push(level)
                 });
                 return resolve(levels)
               }
            })
          }
      },
      handleAddRoom(formName) {
        let _this = this;
        _.forEach(this.roomForm, function(val, key) {
          _this.roomForm[key] = "";
        })
        this.addClassRoomVisible = true;
      },
      async handleUpdateOne(item) {
        let _this = this;
        let params = {
          code: item.code
        }
        let res = await API.getOneRoom(params);
        let towers = await API.getTower({
          parentId: res.data.campus,
          type: 0
        })

        let levels = await API.getTower({
          parentId: res.data.tower,
          type: 1
        })

        if(towers && towers.code == 200) {
          _this.options.tower = [];
          _.forEach(towers.data, function(item) {
             _this.options.tower.push({
               value: item.id + '',
               label: item.name
             })
          });
        }

        if(levels && levels.code == 200) {
          _this.options.towerManagementId = [];
          _.forEach(levels.data, function(item) {
             _this.options.towerManagementId.push({
               value: item.id + '',
               label: item.name
             })
          });
        }

        if(!res && res.code != 200) return;
        _.forEach(this.roomForm, function(val, key) {
          _this.roomForm[key] = res.data[key];
          if(key === 'useing') {
            _this.roomForm[key] = res.data[key].split(',');
          }
        })
        this.addClassRoomVisible = true;
      },
      initOptions() {
        let data = {
          lang: this.$store.getters.language || "cn",
          type: "allChild",
          keys: ["X_YX", "X_XQ", "X_JSLX"]
        };
        queryDic(data)
          .then(res => {
            if (res.code == 200) {
              UTILS.fillSelect({
                campus: "X_XQ",
                departmentCode: "X_YX",
                roomTypes: "X_JSLX"
              }, res.data, this.options);
            }
          })
          .catch(error => {
            console.log(error);
            // this.onSubmit();
          });
      },
      handelCampusChang(item) {
        let _this = this;
        this.options.tower = [];
        this.options.towerManagementId = [];
        this.roomForm.tower = '';
        this.roomForm.towerManagementId = '';
        let params = {
          parentId: item,
          type: 0
        };
        API.getTower(params).then(res => {
           if(res && res.code == 200) {
             _.forEach(res.data, function(item) {
                _this.options.tower.push({
                  value: item.id,
                  label: item.name
                })
             });
           }
        })
      },
      handelTowerChang(item) {
        let _this = this;
        this.options.towerManagementId = [];
        this.roomForm.towerManagementId = '';
        let params = {
          parentId: item,
          type: 1
        };
        API.getTower(params).then(res => {
          if(res && res.code == 200) {
            _.forEach(res.data, function(item) {
              _this.options.towerManagementId.push({
                value: item.id,
                label: item.name
              })
            });
          }
        })
      },
      saveRoom(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.roomForm.useing = this.roomForm.useing.join();
            if(!this.roomForm.code) {
              API.addClassroom(this.roomForm).then(res => {
                if(!res && res.code != 200) return;
                this.$notify.success({
                  title: this.$t('message.prompt'),
                  message: this.$t('message.addSuccess')
                });
                this.$refs[formName].resetFields();
                this.addClassRoomVisible = false;
                this.init();
              })
            } else {
              API.updateClassroom(this.roomForm).then(res => {
                if(!res && res.code != 200) return;
                this.$notify.success({
                  title: this.$t('message.prompt'),
                  message: this.$t('message.editSuccess')
                });
                this.$refs[formName].resetFields();
                this.addClassRoomVisible = false;
                this.init();
              })
            }

          } else {
            return false;
          }
        });
      },
      cancelDialog(formName) {
        this.$refs[formName].resetFields();
        this.addClassRoomVisible = false;
      }
    },
    created() {
      this.initOptions();
      this.init();
    }
  }
</script>

<style lang="scss" scoped>
  .grid-content {
    background-color: #ffffff;
  }
</style>
